package net.pinnoocle.playweb.config;

import net.pinnoocle.playcommon.aop.PassToken;
import net.pinnoocle.playcommon.constant.Constant;
import net.pinnoocle.playcommon.exception.ShopException;
import net.pinnoocle.playcommon.response.ErrorCode;
import net.pinnoocle.playcommon.utils.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ye
 * @Description
 * @create 2021-09-02 12:00
 */
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        //前端请求头中带上token
        String token = httpServletRequest.getHeader(Constant.AUTHORIZATION);
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }else {
            // 执行认证
            if (token == null) {
                throw new ShopException(ErrorCode.TOKEN_INVALID,"登录失败！");
            }
            String userId = JwtUtil.getAudience(token);
            if(userId == null){
                throw new ShopException(ErrorCode.TOKEN_INVALID,"登录过期，请重新登录！");
            }
            // 验证 token
            JwtUtil.verifyToken(token, userId);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
